//校园通相关接口
import HTTPREQUEST from "./http"
import Taro from "@tarojs/taro";

//校园通默认根路径
export const BASE_CAMPUS_URL = "https://campus.lancooedu.com:9001"

export const get = (url, data?, header?, loading?, isBackAll?) => HTTPREQUEST.get(`${BASE_CAMPUS_URL}${url}`, data, header, loading, isBackAll)
export const post = (url, data?, header?, loading?) => HTTPREQUEST.post(`${BASE_CAMPUS_URL}${url}`, data, header, loading)
export const put = (url, data?, header?, loading?) => HTTPREQUEST.put(`${BASE_CAMPUS_URL}${url}`, data, header, loading)
export const del = (url, data?, header?, loading?) => HTTPREQUEST.delete(`${BASE_CAMPUS_URL}${url}`, data, header, loading)

type ResultType = {
   errCode: number | null
   errMsg: string
   expiresIn: number
   ticket: string
};

//统一处理http&业务response
async function responseHandler<T>(response: Promise<ResultType>, showToast: boolean = false) {
   //HTTP请求层response统一处理
   let res: ResultType | null = null
   try {
      res = await response;
   } catch (err) {
      //默认无异常弹窗提示
      if (showToast) {
         await Taro.showToast({ icon: 'none', title: "网络错误" })
      }
      throw new Error("网络错误")//与业务（接口）层统一catch处理异常
   }

   //业务（接口）层result返回统一处理
   if (res?.errCode == 0) {
      return res
   }
}

//获取公众号assessToken
interface TicketData {
   ticket: string//
   expires_in: number//有效时长
   errcode: string
   errmsg: string
}
export const getTicket = (schoolId: string) => responseHandler<TicketData>(get(`/wxapi/getJsapiTicket`, { schoolId: schoolId }));
